import {EventEmitter, Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {FormControl} from '@angular/forms';

import {IpostData} from './post-data.interface';

@Injectable()
export class AuthService {
  isLogin = false;
  authStatus = new EventEmitter<number>();
  // 1 登录
  // 2 退出
  // 3 token过期
  user: IpostData = {
    userName: '',
    password: '',
    email: '',
    telphone: ''
  };
  constructor(private http: Http) {}
  login(postData) {
    return this.http.post('http://localhost:3000/users/login', postData)
      .map(
        (response: Response) => {
          const data = response.json();
          if (data.code === 1) {
            this.isLogin = true;
            this.authStatus.emit(1);
            localStorage.setItem('login', JSON.stringify(data));
          }
          return data;
        }
      );
  }
  logout() {
    this.isLogin = false;
    this.authStatus.emit(2);
    localStorage.removeItem('login');
  }
  register(postData: IpostData) {
    return this.http.post('http://localhost:3000/users/register', postData)
      .map(
        (response: Response) => {
          const data = response.json();
          return data;
        }
      );
  }
  checkUserName(userInfo) {
    return this.http.post('http://localhost:3000/users/checkUserName', userInfo)
      .map(res => res.json());
  }

}
